/*
 *  pricePrices.c
 *  PriceCompareDS
 *
 *  Created by Stacy Haponik on 5/27/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fat.h>
//#include <curses.h>
#include <nds.h>
#ifndef utilities.c
#define utilities.c
#endif

/* Constants */
#define N_COLUMNS		 10
#define DATE_CAPACITY		 10
#define STORE_CAPACITY		 20
#define ITEMTYPE_CAPACITY	 10
#define ITEMNAME_CAPACITY	 21
#define UNIT_CAPACITY		  4
#define NOTES_CAPACITY		200
#define ARRAYOFPRICES_CAPACITY	 50


/* Macros */

/* READ_STRING_FIELD: reads a string field from myFile into arrayOfPrices[j]
 * Arguments:
 * 	FIELD_NAME: the name of the member of arrayOfPrices to be read
 * 	STRING_CAPACITY: the dimension of arrayOfPrices[j].FIELD_NAME. Must be a positive integer literal.
 */
#define READ_STRING_FIELD(FIELD_NAME, STRING_CAPACITY)				\
{ /* allow declaring new variables */						\
	char myString[STRING_CAPACITY];						\
	iprintf("\n" #FIELD_NAME ": "); /* e.g. "\ndate: " */			\
	i=0;									\
	while (1) {								\
		myChar = fgetc(myFile);						\
		if (myChar == '\t' || myChar == '\n' || myChar == 255){		\
			break; /* out of the while loop */			\
		}								\
		if (i < STRING_CAPACITY-1){					\
			myString[i]=myChar;					\
			i++;							\
		}								\
	}									\
	myString[i] = '\0';							\
	iprintf("%s",myString);							\
	strcpy(arrayOfPrices[j].FIELD_NAME,myString);				\
}


/* READ_NUMERICAL_FIELD: reads a field containing a numeral from myFile into arrayOfPrices[j]
 * Arguments:
 * 	FIELD_NAME: the name of the member of arrayOfPrices to be read
 *      MAX_CHARS: the maximum number of characters to scan. Must be an integer literal.
 * 	CONVERSION_FUNCTION: the name of the function to convert the string into the desired data type
 */
#define READ_NUMERICAL_FIELD(FIELD_NAME, MAX_CHARS, CONVERSION_FUNCTION)	\
{ /* allow declaring new variables */								\
	char myString[MAX_CHARS+1];										\
	iprintf("\n" #FIELD_NAME ": "); /* e.g. "\ndate: " */			\
	i=0; 															\
	while ((myChar = fgetc(myFile)) != 255) {						\
		if (myChar == '\t' || myChar == '\n' || myChar == 255){		\
			iprintf("MyChar is a terminator.\n");					\
			break; /* out of the while loop */						\
		}															\
		if (i < MAX_CHARS){											\
			myString[i]=myChar;										\
			i++;													\
		}															\
		iprintf("u=%d, myChar=%d\n",i,myChar);						\
	}																\
	myString[i] = '\0';												\
	iprintf("%s",myString);											\
	arrayOfPrices[j].FIELD_NAME = CONVERSION_FUNCTION(myString);	\
}																	\


#define TEST_FOR_NEWLINE_OR_EOF					\
	if (myChar == '\n'){						\
		continue;	/* for loop */				\
	} else if (myChar == 255){					\
		iprintf ("\nFound EOF\n");				\
		break;		/* out of the for loop */	\
		}										\




typedef struct {
	char date[DATE_CAPACITY];
	char store[STORE_CAPACITY];
	char itemType[ITEMTYPE_CAPACITY];
	char itemName[ITEMNAME_CAPACITY];
	int	size;
	char unit[UNIT_CAPACITY];
	double price;
	int sale;
	int coupon;
	char notes[NOTES_CAPACITY];
} aPrice;

aPrice arrayOfPrices[ARRAYOFPRICES_CAPACITY];			//TODO: fix this, size appropriately
char arrayOfTypes[ITEMTYPE_CAPACITY][ARRAYOFPRICES_CAPACITY];
int numOfTypes=0;

int priceCount=0;

int numberOfPrices(void){					//determines how many prices are in prices.txt
	FILE *myFile;
	myFile=fopen("fat:prices.txt", "r"); 
	if (!myFile){
		iprintf("Couldn't open prices.txt for reading\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3");
		return 0;
	}
	else {
		int i=numberOfLinesInFile(myFile);
		fclose(myFile);
		return i-1;
	}
}

int readInPrices(void){
	FILE *myFile;
	myFile=fopen("fat:prices.txt", "r"); 
	if (!myFile){
		iprintf("Couldn't open prices.txt for reading.");
		return 0;
	}
	else {
		priceCount=numberOfPrices();		//fix this-- number of prices should return -1 if it fails.
		iprintf("Number of Prices: %i",priceCount);
	}
	char myChar;
	myFile=fopen("fat:prices.txt", "r");
	//myPrices arrayOfPrices[storeCount];			//make an array of store structs, of size to fit all the stores
	int j=0;
	myChar = fgetc(myFile);
	while ( myChar!='\n'){		//loop through till the end of the first line, since it's just a header
		myChar = fgetc(myFile);
	}
	for (j=0; j < priceCount; j++){			//loop until all prices are added to the arrayOfPrices
		//		iprintf("In the loop processing statements");
		int i=0;
		int column=1;		//what column are we on?
		// iprintf("\nIn the while loop, column=%i",column);
		
		READ_STRING_FIELD(date, DATE_CAPACITY) /* macro, therefore no semicolon */
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_STRING_FIELD(store, STORE_CAPACITY)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_STRING_FIELD(itemType, ITEMTYPE_CAPACITY)
		{ /* allow declaring new variables */
			int newType=1;
			int k=0;
			for (k=0;(k<numOfTypes)&&newType==1;k++){
				if((strcmp(arrayOfTypes[k],arrayOfPrices[j].itemType)==0)){				//check to see if this type already exists in the list
					newType=0;
					}
				}
			if (newType==1){
				numOfTypes++;
				strcpy(arrayOfTypes[numOfTypes],arrayOfPrices[j].itemType);
				}
		}
		TEST_FOR_NEWLINE_OR_EOF

		
		READ_STRING_FIELD(itemName, ITEMNAME_CAPACITY)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_NUMERICAL_FIELD(size, 4, atoi)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_STRING_FIELD(unit, UNIT_CAPACITY)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_NUMERICAL_FIELD(price, 10, atof)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_NUMERICAL_FIELD(sale, 1, atoi)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_NUMERICAL_FIELD(coupon, 1, atoi)
		TEST_FOR_NEWLINE_OR_EOF
				
		READ_STRING_FIELD(notes, NOTES_CAPACITY)
		TEST_FOR_NEWLINE_OR_EOF

		/* If we're not at the end of the line, we should be. */
		while (myChar != '\n' && myChar != 255) {myChar = fgetc(myFile);}
		
		iprintf("Reached end of row %i\n",j);
		i=0;
		//  iprintf("Row %i. PriceCount=%i\n",j, priceCount);

		if (myChar == 255){
			break;
			}

	} /* end of for loop */
	fclose(myFile);
	iprintf("End of readInPrices\n");
	return 0;
}

int printPrices(void){
	iprintf("begin of printPrices\n");
	//	readInPrices();
	readInPrices();
	iprintf("past readInPrices\n");
	int i=0;
	//	iprintf("i=%i. priceCount=%i\n",i,priceCount);
	for (i=0; i<priceCount; i++){	//loop until we reach the last price
		printf("%20s $%.2f/%4s\n",arrayOfPrices[i].itemName, (arrayOfPrices[i].price/arrayOfPrices[i].size),arrayOfPrices[i].unit); /* still uses magic numbers */
	}
	return 0;
}
/*
12345678901234567890123456789012
FRUIT
AvocadosHaveLongName $12.29/each
    Bloom     $1.29/each		
	Safeway	  $2.00/each		
	Bloom     $0.79/each	(s)	
	char date[10];
	char store[20];
	char itemType[10];
	char itemName[20];
	int	size;
	char unit[4];
	double price;
	int sale;
	int coupon;
	char notes[200];

*/
int priceScreen(){
	printPrices();
	int addPrice=0;			//if true, then we should display the "add price" keyboard and questions.
	int i=0;			//iterator to store our spot in the "add price" buffer.
	int question=1;			//which question are we on?
	int maxQuestion=N_COLUMNS;	//how many questions do I have?
	int prompt=0;			//is it time to ask a question?
	int answerLength=0;
	int maxAnswerLength=ITEMNAME_CAPACITY;	//how long of an answer should the prompt accept?
	keyboardDemoInit();
	//	keyboardHide();
	//	keyboardShow();
	
	char buffer[sizeof(aPrice)];	//add store buffer-- size is maximum possible size for a line to be saved to prices.txt.
	iprintf("%i",sizeof(aPrice));
	while(1){		//loop until you get input
		scanKeys();
		int pressed = keysDown();   // buttons pressed this loop
		
		if ( pressed & KEY_A){
			//			consoleClear();
			addPrice=1;
			prompt=1;
			//			printPrices();
			keyboardShow();
			iprintf("Let's add a price entry!");
		}		//add a store
		if ( pressed & KEY_L){
			iprintf("Swapping to shopping list screen");
			return 0;
			break;
		}		//swap to "price entries" screen
		if ( pressed & KEY_R){
			iprintf("Swapping to Stores screen");
			return 2;
			break;
		}		//swap to calculator mode
		
		if ( pressed & KEY_B){
			iprintf("Stored item types:\n");
			int k=0;
			for (k=0;k<numOfTypes;k++){
				iprintf("%s\n",arrayOfTypes[k]);
				}
		}
		
		
		int key = keyboardUpdate();
		
		if (addPrice==1){						//TODO FIX THIS
			//			consoleSelect(&bottomScreen);
			if (prompt==1){
				prompt=0;
				switch (question){
					case 1:
						iprintf("\nDate: ");
						break;
					case 2:
						iprintf("\nStore: ");
						break;
					case 3:
						iprintf("\nType: ");
						break;
					case 4:
						iprintf("\nItem: ");
						break;
					case 5:
						iprintf("\nSize: ");
						break;
					case 6:
						iprintf("\nUnitss: ");
						break;
					case 7:
						iprintf("\nPrice: ");
						break;
					case 8:
						iprintf("\nSale?: ");
						break;
					case 9:
						iprintf("\nCoupon?: ");
						break;
					case 10:
						iprintf("\nNotes: ");
						break;
					default:
						iprintf("\nOoops. I don't know how I got here.");
						break;
				}
			}			//print the appropriate prompt
			
			
	/*	char date[DATE_CAPACITY];
	char store[STORE_CAPACITY];
	char itemType[ITEMTYPE_CAPACITY];
	char itemName[ITEMNAME_CAPACITY];
	int	size;
	char unit[UNIT_CAPACITY];
	double price;
	int sale;
	int coupon;
	char notes[NOTES_CAPACITY];
	*/
			
			if (key>0&&key!=255){
				//					iprintf("%c", key);
				if ((key==10)||(answerLength>=maxAnswerLength)){
					buffer[i]='\t';
					prompt=1;
					question++;
					i++;
					answerLength=0;
					//					iprintf("Adding a tab");
				}		//if there's a return character
				else if(key>=32){
					buffer[i]=key;
					iprintf("%c",key);
					i++;
					answerLength++;
				}		//if there's a letter, number, or space
				else if(key==8){
					i--;
					answerLength--;
					iprintf("%c",key);
				}		//if there's a backspace character
				if (question>maxQuestion){
					i--;		//remove the trailing tab character
					buffer[i]='\0';
					question=1;
					addPrice=0;
					i=0;
					answerLength=0;
					FILE *myFile=fopen("fat:prices.txt", "a"); 
					fprintf(myFile,"\n%s",buffer);
					fclose(myFile);
					consoleClear();
					iprintf("\nAdded Price: %s\n",buffer);
					printPrices();
					keyboardHide();
				}				//print to file, reset iterators
				key=0;
			}
			//			consoleSelect(&topScreen);
		}		//loop to add a price entry
		swiWaitForVBlank();
	}
}